//
//  GYShopCollectionViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/5.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

static NSString *verFavoritesCellIdentifier = @"verFavoritesCellIdentifier";
static NSString *horFavoritesCellIdentifier = @"horFavoritesCellIdentifier";

#import "GYShopCollectionViewController.h"
#import "GYNoAddressView.h"
#import "GYNetWorkTools.h"
#import "GYVerFavoritesCell.h"
#import "GYHorFavoritesCell.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSearchViewController.h"
#import "GYSystemMessageViewController.h"
#import "GYShopHomeViewController.h"
#import "GYStoreInfoViewController.h"

@interface GYShopCollectionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/** 没有商品收藏的视图 */
@property (nonatomic, strong) GYNoAddressView *NoGoodsView;

/** 没有店铺收藏的视图 */
@property (nonatomic, strong) GYNoAddressView *NoShopView;

/** 视图 */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *favoritesShops;

/** 布局 */
@property (nonatomic, getter=isLayout) BOOL layout;

@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, getter=isHasmore) BOOL hasmore;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 换粗cell的 */
@property (nonatomic, strong) NSMutableDictionary *cachesheight;

/** 选择栏 */
@property (nonatomic, weak) UISegmentedControl *segementControlelr;
@end

@implementation GYShopCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.currentIndex = 1;
    self.hasmore = YES;
    
    //初始化
    [self setupUI];
    
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化导航栏中间视图
    UISegmentedControl *segementControlelr = [[UISegmentedControl alloc] initWithItems:@[@"商品收藏",@"店铺收藏"]];
    segementControlelr.frame = CGRectMake(0, 0, 200, 30);
    segementControlelr.selectedSegmentIndex = self.defaultIndex;
    segementControlelr.tintColor = RGBColor(0, 158, 214);//RGBColor(68, 165, 25);
    [segementControlelr setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    [segementControlelr addTarget:self action:@selector(changedView:) forControlEvents:UIControlEventValueChanged];
    self.segementControlelr = segementControlelr;
    
    self.navigationItem.titleView  = segementControlelr;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(rightButClick) button:nil];
    
    //初始化视图
    [self setupCollectionView];
    
    //初始化没有商品的图
    self.NoGoodsView = [self getNoShopView:@"favorite_w" head:@"您还没有关注任何商品" foot:@"可以去看看哪些商品值得收藏"];
    
    self.NoShopView = [self getNoShopView:@"store_w" head:@"您还没有关注任何店铺" foot:@"可以去看看哪些店铺值得收藏"];
    if (self.defaultIndex == 0) {
        self.layout = YES;
        [self loadFavoritesGoods:@"1"];
        
    }else {
        self.layout = NO;
        [self loadFavoritesStores:@"1"];
    }
    
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, self.view.height-0) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = RGBColor(245, 245, 245)
;
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"GYVerFavoritesCell" bundle:nil] forCellWithReuseIdentifier:verFavoritesCellIdentifier];
    [collectionView registerNib:[UINib nibWithNibName:@"GYHorFavoritesCell" bundle:nil] forCellWithReuseIdentifier:horFavoritesCellIdentifier];
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadMoreData {
    if (self.layout) {
        [self loadFavoritesGoods:[NSString stringWithFormat:@"%zd",self.currentIndex]];
    }else {
        [self loadFavoritesStores:[NSString stringWithFormat:@"%zd",self.currentIndex]];
    }
}


- (void)loadFavoritesGoods:(NSString *)curpage {
    if (self.isHasmore) {
        [EasyLodingView showLodingText:@"正在加载..."];
        [GYNetWorkTools requestUserCommodityCollection:@"" page:@"20" success:^(NSDictionary *obj) {
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                [self.collectionView.mj_footer endRefreshing];
                [EasyLodingView hidenLoding];
                self.currentIndex += 1;
                self.hasmore = [[datas objectForKey:@"hasmore"] boolValue];
                NSArray *favorites_list = [datas objectForKey:@"favorites_list"];
                NSArray *goods = [GYGoodsFavorites laodGoodsFavorites:favorites_list];
                [self.favoritesShops addObjectsFromArray:goods];
                if (self.favoritesShops.count == 0) {
                    self.NoGoodsView.hidden = NO;
                }else {
                    self.NoGoodsView.hidden = YES;
                    [self.collectionView reloadData];
                }
            }else if (code == 400) {
                [EasyTextView showText:@"加载数据出错..."];
                [EasyLodingView hidenLoding];
                NSLog(@"网络加载数据=====%@",[datas objectForKey:@"error"]);
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"加载数据出错..."];
            [EasyLodingView hidenLoding];
            NSLog(@"laodUserCommodityCollectionFailed====%@",error);
        }];
    }else {
        [self.collectionView.mj_footer endRefreshing];
        [EasyTextView showText:@"没有更多数据了!"];
        NSLog(@"没有数据加载/...");
    }
}

- (void)loadFavoritesStores:(NSString *)curpage {
    if (self.isHasmore) {
        [EasyLodingView showLodingText:@"正在加载..."];
        [GYNetWorkTools requestUserShopCollection:@"" page:@"20" success:^(NSDictionary *obj) {
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                [self.collectionView.mj_footer endRefreshing];
                [EasyLodingView hidenLoding];
                self.currentIndex += 1;
                self.hasmore = [[datas objectForKey:@"hasmore"] boolValue];
                NSArray *favorites_list = [datas objectForKey:@"favorites_list"];
                NSArray *stores = [GYStoreFavotites loadStoreFavorites:favorites_list];
                [self.favoritesShops addObjectsFromArray:stores];
                if (self.favoritesShops.count == 0) {
                    self.NoShopView.hidden = NO;
                }else {
                    self.NoShopView.hidden = YES;
                    [self.collectionView reloadData];
                }
                
            }else if (code == 400) {
                [EasyTextView showText:@"加载数据出错..."];
                [EasyLodingView hidenLoding];
                NSLog(@"网络加载数据=====%@",[datas objectForKey:@"error"]);
            }
            
        } error:^(NSError *error) {
            [EasyTextView showText:@"加载数据出错..."];
            [EasyLodingView hidenLoding];
            NSLog(@"loadUserShopCollectionFailed===%@",error);
        }];
    }else {
        [self.collectionView.mj_footer endRefreshing];
        [EasyTextView showText:@"没有更多数据了!"];
    }
}

- (void)changedView:(UISegmentedControl *)segementController {
    switch (segementController.selectedSegmentIndex) {
        case 0:
        {
            self.layout = YES;
            self.currentIndex = 1;
            self.hasmore = YES;
            [self.favoritesShops removeAllObjects];
            [self loadFavoritesGoods:[NSString stringWithFormat:@"%zd",self.currentIndex]];
        }
            break;
            
        case 1:
        {
            self.layout = NO;
            self.currentIndex = 1;
            self.hasmore = YES;
            [self.favoritesShops removeAllObjects];
            [self loadFavoritesStores:[NSString stringWithFormat:@"%zd",self.currentIndex]];
        }
            break;
            
        default:
            break;
    }
}

- (void)rightButClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                weakSelf.tabBarController.selectedIndex = 0;
                [weakSelf.tabBarController.tabBar setHidden:NO];
            }
                break;
                
            case 1:
            {
                GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
                [self.navigationController pushViewController:searchVC animated:YES];
            }
                break;
                
            case 2:
            {
                GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];

            }
                break;
                
            default:
                break;
        }
    };
    basePopoverVC.titles = @[@"首页",@"搜索",@"消息"];
    basePopoverVC.images = @[@"home_w",@"search_w",@"message_w"];
    
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];
}

#pragma mark -- UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.favoritesShops.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isLayout) {
        GYVerFavoritesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:verFavoritesCellIdentifier forIndexPath:indexPath];
        GYGoodsFavorites *goods = self.favoritesShops[indexPath.item];
        cell.currentRow = indexPath.item;
        cell.goods = goods;
        __weak typeof(self) weakSelf = self;
        cell.deleteFavoritesGoodsCallBack = ^(NSInteger currentRow) {
            [GYNetWorkTools requestCancelGoodsfavorites:goods.goods_id success:^(NSDictionary *obj) {
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    [EasyTextView showSuccessText:@"取消商品收藏成功!"];
                    [weakSelf.favoritesShops removeObjectAtIndex:currentRow];
                    [weakSelf.collectionView reloadData];
                }else if (code == 400) {
                    [EasyTextView showText:@"取消商品收藏失败!"];
                    NSLog(@"网络删除出错...");
                }
            } error:^(NSError *error) {
                [EasyTextView showText:@"取消商品收藏失败!"];
                NSLog(@"loadCancelGoodsfavoritesFailed===%@",error);
            }];
        };
        
        return cell;
    }else {
        GYHorFavoritesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:horFavoritesCellIdentifier forIndexPath:indexPath];
        GYStoreFavotites *store = self.favoritesShops[indexPath.item];
        cell.currentRow = indexPath.item;
        cell.stores = store;
        __weak typeof(self) weakSelf = self;
        cell.deleteFavoritesStoreCallBack = ^(NSInteger currentRow) {
            //删除店铺收藏
            [GYNetWorkTools requestCancelStoreFavorites:store.store_id success:^(NSDictionary *obj) {
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    [EasyTextView showSuccessText:@"删除店铺收藏成功!"];
                    [weakSelf.favoritesShops removeObjectAtIndex:currentRow];
                    [weakSelf.collectionView reloadData];
                }else if (code == 400) {
                    [EasyTextView showText:@"删除店铺收藏失败!"];
                    NSLog(@"网络删除出错...");
                }
            } error:^(NSError *error) {
                [EasyTextView showText:@"删除店铺收藏失败!"];
                NSLog(@"loadCancelStoreFavoritesFailed====%@",error);
            }];
        };
        
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isLayout) {
        
        //GYVerFavoritesCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"GYVerFavoritesCell" owner:nil options:nil] firstObject];
        GYGoodsFavorites *goods = self.favoritesShops[indexPath.item];
        CGFloat height = [[self.cachesheight objectForKey:goods.goods_id] floatValue];
        if (height != 0) {
            return CGSizeMake((ScreenWidth-5)/2, height);
        }else {
            CGFloat nameHeight = [goods.goods_name boundingRectWithSize:CGSizeMake((ScreenWidth-5)/2, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil].size.height;
            CGFloat priceHeight = [[NSString stringWithFormat:@"%@",goods.goods_price] boundingRectWithSize:CGSizeMake((ScreenWidth-5)/2, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
            CGFloat rowHeight = (ScreenWidth-5)/2+nameHeight+priceHeight+30;
            
            [self.cachesheight setObject:@(rowHeight) forKey:goods.goods_id];
            
            return CGSizeMake((ScreenWidth-5)/2, rowHeight);
        }
    }else {
       return CGSizeMake(ScreenWidth, 70);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //判断当前选中商品还是 商店
    if (self.segementControlelr.selectedSegmentIndex == 0) {
        //商品
        GYShopHomeViewController *shopHomeVC =[[GYShopHomeViewController alloc] init];
        shopHomeVC.goods_id = [self.favoritesShops[indexPath.item] goods_id];
        [self.navigationController pushViewController:shopHomeVC animated:YES];
    }else {
        //店铺
        GYStoreInfoViewController *storeInfoVC = [[GYStoreInfoViewController alloc] initWithNibName:@"GYStoreInfoViewController" bundle:nil];
        storeInfoVC.store_id = [self.favoritesShops[indexPath.item] store_id];
        [self.navigationController pushViewController:storeInfoVC animated:YES];
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.isLayout ? 5 : 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.isLayout ? 5 : 0;
}

#pragma mark -- 封装的方法

- (GYNoAddressView *)getNoShopView:(NSString *)imageName head:(NSString *)head foot:(NSString *)foot {
    
    GYNoAddressView *shopCollectionView = [[[NSBundle mainBundle] loadNibNamed:@"GYNoAddressView" owner:nil options:nil] firstObject];
    shopCollectionView.frame = self.view.bounds;
    shopCollectionView.markImageView.image = [UIImage imageNamed:imageName];
    shopCollectionView.headLable.text = head;
    shopCollectionView.footLable.text = foot;
    shopCollectionView.hidden = YES;
    [shopCollectionView.addBtu setTitle:@"随便逛逛" forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    shopCollectionView.addNewAddressCallBack = ^{
        //跳转到首页
        weakSelf.tabBarController.selectedIndex = 0;
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    [self.view addSubview:shopCollectionView];
    
    return shopCollectionView;
}

#pragma mark -- 懒加载

- (NSMutableArray *)favoritesShops {
    if (!_favoritesShops) {
        _favoritesShops = [NSMutableArray array];
    }
    
    return _favoritesShops;
}

- (NSMutableDictionary *)cachesheight {
    if (!_cachesheight) {
        _cachesheight = [NSMutableDictionary dictionary];
    }
    
    return _cachesheight;
}



















@end
